/****************************************************
          File Name:12-5.cpp
          Author: Abby Cin
          Mail: abbytsing@gmail.com
          Created Time: Thu 01 Jan 2015 12:41:07 PM CST
*****************************************************/

#include"12-5.h"
#include<cstdlib>
#include<ctime>

const int MIN_PER_HR = 60;
using std::cout;
using std::cin;
using std::endl;
using std::ios_base;

bool newcustomer(double x)
{
    return (std::rand() * x / RAND_MAX < 1);
}

int main()
{
    std::srand(std::time(0));

    cout << "Case Study: Bank of Heather Automatic Teller\n";
    cout << "Enter maxium size of queue: ";
    int qs;
    cin >> qs;
    cout << "Enter the number of simulation hours:";
    int hours;
    cin >> hours;
    long cyclelimit;
    cyclelimit = MIN_PER_HR * hours;

    double perhour = 0.0; 

    cout << "Now simulate the time...\n";

    Queue line(qs);
    double line_wait = 0.0;
    double min_per_cust = 0.0;
    long turnaways = 0;
    long customers = 0;
    long served = 0;
    long sum_line = 0;
    long wait_time = 0;
    Item temp;

    for(;;)
    {
        min_per_cust = MIN_PER_HR / perhour;

        for(int cycle = 0; cycle < cyclelimit; cycle++)
        {
            if(newcustomer(min_per_cust))
            {
                if(line.isfull())
                    turnaways++;
                else
                {
                    customers++;
                    temp.set(cycle);
                    line.enqueue(temp);
                }
            }

            if(wait_time <=0 && !line.isempty())
            {
                line.dequeue(temp);
                wait_time = temp.ptime();
                line_wait += cycle - temp.when();
                served++;
            }

            if(wait_time > 0)
                wait_time--;

            sum_line += line.queuecount();
        }

        if(customers > 0)
        {
            if((line_wait / served) >= 1.0)
                break;
        }

        perhour += 1;
    }
    cout << "Average wait time equal 1 min, then shall have: " << perhour << " customers per hour\n";

    return 0;
}
